#include "Protocol.hpp"
#include "TcpServer.hpp"
#include "Calculator.hpp"
#include "Daemon.hpp"

#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <memory>

using namespace std;

// 网络负责IO发送
// handler_request字节流数据解析和调用业务处理方法
string handler_request(string& inbufferstream,bool* ok)
{
    *ok = true;
    // 1. 构建响应对象和计算器对象
    Calculator calculator;
    unique_ptr<Factory> factory = make_unique<Factory>();
    std::shared_ptr<Request>req = factory->BuildRequest();

    std::string total_send_message;

    // 2、分析字节流，判断是否是一个完整的报文，同时处理多个报文
    std::string buffer;
    while(DeCode(inbufferstream,&buffer))
    {
        // 3、反序列化
        if(!req->Deserialize(buffer))
        {
            cout << "Deserialize fail" << endl;
            *ok = false;
            return string();
        }
        cout << "Deserialize success" << endl;
        req->Debug(); 
        // 4、处理
        std::shared_ptr<Response>resp = calculator.Cal(req);
        // 5、对response进行序列化
        std::string send_message;
        resp->Serialize(&send_message);
        // 6、构建完成字符串级别的响应报文
        send_message = EnCode(send_message);
        total_send_message += send_message;
    }
    return total_send_message;
}

void Usage(string proc)
{
    cout << proc << " serverport" << endl;
}

int main(int argc , char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    uint16_t serverport = stoi(argv[1]);

    Daemon(false,false);

    unique_ptr<TcpServer> up = make_unique<TcpServer>(serverport,handler_request);
    up->Loop();

    return 0;
}